package com.ysd.util;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 *
 * Base64与xml相互转换
 *@author Bai
 *@since 2023-11-29
 * */
public class Base64Util {
    public static String encodeToString(String plainText) {
        byte[] bytes = plainText.getBytes(StandardCharsets.UTF_8);
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String decodeToString(String base64String) {
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);
        return new String(decodedBytes, StandardCharsets.UTF_8);
    }

    public static String encodeToString(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] decodeToBytes(String base64String) {
        return Base64.getDecoder().decode(base64String);
    }
    public  static  void setXmlValue(String reportXml,String node,String replaceNodeValue) throws Exception{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(reportXml)));
        // 替换节点值
        replaceNodeValue(doc, node, replaceNodeValue);
    }

    public static void main(String[] args)  throws Exception {
       // String base64String = new String(Files.readAllBytes(Paths.get("base64.txt"))); // 从文件中读取Base64字符串﻿

       // String xmlString = decodeToString(base64String);
//        String xmlString ="\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Report xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition\"><dd:Name xmlns:dd=\"http://schemas.datadynamics.com/reporting/2005/02/reportdefinition\">Report</dd:Name><Body><ColumnSpacing>0cm</ColumnSpacing><Height>4cm</Height><ReportItems><CustomReportItem Name=\"输入字段1\"><Type>InputField</Type><Top>3.25cm</Top><Left>2.499cm</Left><Width>11.001cm</Width><Height>0.75cm</Height><Style><FontFamily>微软雅黑</FontFamily></Style><CustomProperties><CustomProperty><Name>Value</Name><Value>测试页面配置</Value></CustomProperty></CustomProperties></CustomReportItem></ReportItems><Style><BackgroundColor>#f44336</BackgroundColor></Style></Body><BottomMargin>0.25cm</BottomMargin><LeftMargin>0.25cm</LeftMargin><RightMargin>0.25cm</RightMargin><TopMargin>0.25cm</TopMargin><PageHeight>42cm</PageHeight><PageWidth>29.7cm</PageWidth><Width>13.5cm</Width><CustomProperties><CustomProperty><Name>DisplayType</Name><Value>Page</Value></CustomProperty><CustomProperty><Name>SizeType</Name><Value>Default</Value></CustomProperty><CustomProperty><Name>PaperOrientation</Name><Value>Portrait</Value></CustomProperty></CustomProperties></Report>";
//        xmlString = xmlString.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>","").trim();
//        xmlString = xmlString.substring(1);
//
//        System.out.println(xmlString);
//         // String xmlString = new String(Files.readAllBytes(Paths.get("reportXml.txt")));
//        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//        DocumentBuilder builder = factory.newDocumentBuilder();
//        Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
//        // 替换节点值
//        String bottomMargin = getTextValue(doc, "BottomMargin");
//        System.out.println(bottomMargin);
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Report xmlns=\"\"><Body><Data>...</Data></Body></Report>";

        // 截取 Report 元素及其后面的内容
        int index = xml.indexOf("<Report");
        if (index >= 0) {
            xml = xml.substring(index);
        }
        System.out.println(xml);
    }

    // 辅助方法：获取节点值
    private static String getTextValue(Document doc, String tagName) {
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if (nodeList != null && nodeList.getLength() > 0) {
            return nodeList.item(0).getTextContent();
        } else {
            return null;
        }
    }


    public static String convertToString(Document doc) throws TransformerException {
        // 创建 TransformerFactory 和 Transformer 对象
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        // 将 Document 转换为 DOMSource
        DOMSource source = new DOMSource(doc);

        // 创建 StringWriter 来接收转换后的结果
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        // 执行转换
        transformer.transform(source, result);

        // 获取转换后的字符串
        String xmlString = writer.toString();

        return xmlString;
    }

    // 辅助方法：替换节点值
    public static void replaceNodeValue(Document doc, String tagName, String newValue) {
        Element element = (Element) doc.getElementsByTagName(tagName).item(0);
        element.setTextContent(newValue);
    }

    // 辅助方法：将Document转换为XML字符串
    private static String convertDocumentToString(Document doc) throws Exception {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.getBuffer().toString();
    }





}
